import { _decorator, Component, Node, Vec2 } from 'cc';
import { MaxHeight } from '../../consts';
import { EventName } from '../../consts/events';
import Utils from '../../utils';
const { ccclass } = _decorator;

@ccclass('Background')
export class Background extends Component {
    private speed: number = 0;
    private initPos: Vec2;
    private isInit: boolean = false;
    init(speed: number) {
        if (this.isInit) return;
        this.isInit = true;
        this.speed = speed;
        this.initPos = new Vec2(this.node.position.x, this.node.position.y);
        this.enabled = false;
    }
    protected onLoad(): void {
        Utils.events.on(EventName.StartGame, this.startGame, this);
        Utils.events.on(EventName.PauseGame, this.pauseGame, this);
        Utils.events.on(EventName.ResumeGame, this.resume, this);
        Utils.events.on(EventName.EndGame, this.endGame, this);
    }
    protected onDestroy(): void {
        Utils.events.off(EventName.StartGame, this.startGame, this);
        Utils.events.off(EventName.PauseGame, this.pauseGame, this);
        Utils.events.off(EventName.ResumeGame, this.resume, this);
        Utils.events.off(EventName.EndGame, this.endGame, this);
    }
    private startGame() {
        this.node.setPosition(this.initPos.x, this.initPos.y);
        this.enabled = true;
    }
    private pauseGame() {
        this.enabled = false;
    }
    private endGame() {
        this.enabled = false;
    }
    private resume() {
        this.enabled = true;
    }
    protected update(dt: number): void {
        let y = this.node.position.y - this.speed * dt;
        if (y < -(MaxHeight * 1.5)) {
            y = y + MaxHeight * 3;
        }
        this.node.setPosition(this.node.position.x, y);
    }
}

export const addBackgroundEntity = (node: Node, speed: number) => {
    const bg = node.addComponent(Background);
    bg.init(speed);
};
